var express = require("express");
var router = express.Router();
const multer = require("multer");
var sqlobj = require("../db/sql_utils");

// image upload
var stroage = multer.diskStorage({
  destination: function (req, file, cd) {
    if(process.env.environment && process.env.environment==="PRO"){
      console.log("process.env.environment:",process.env.environment)
      cd(null, "/root/images");
    }else{
      cd(null, "./public/images");
    }
  },
  filename: function (req, file, cb) {
    var fileFormat = file.originalname.split(".");
    // cb(null, `${Date.now()}-${file.originalname}`)
    cb(null, `${Date.now()}.` + fileFormat[fileFormat.length - 1]);
  },
});
var upload = multer({ storage: stroage });

/**
 * @api {POST} /api/upload 文件上传
 * @apiDescription 文件上传
 * @apiName upload
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup File
 * @apiParam  {File} files  文件名字
 * @apiHeader {String} Content-Type mutipart/form-data 文件上传
 * @apiVersion 1.0.0
 */
router.post("/api/upload", upload.any(), function (req, res, next) {
  console.log(req.files);
  let url = `http://${req.headers.host}/images/${req.files[0].filename}`;
  if (!req.files) return res.json({ code: 400, message: "Upload failed" });
  return res.json({ code: 200, message: "Uploaded successfully", url: url });
});
module.exports = router;
